import * as echarts from 'echarts'
import moment from 'moment'
import request from '@/utils/request'

export function queryTableData(query) {
  return request({
    url: '/timeAnalysis/continous/listAll',
    method: 'get',
    params: query,
    timeout: 30000
  })
}

export function getTopId(query) {
  return request({
    url: '/parameter/getMachineGroupByMachineTypeId',
    method: 'get',
    params: query
  })
}

export function getSon(query) {
  return request({
    url: 'interface/api/sonAll',
    method: 'get',
    params: query
  })
}

let finaVal = []

var colors = ['#00ff00', '#ff0000', '#ffff00', '#0000ff', 'black']
var state = ['RUN', 'DOWM', 'IDLE', 'PM', 'OFF']

let _terget = {}

let labes = []
export const chartOptios = (data, machineId, index, dataTime) => {
  _terget = {}
  labes = []
  finaVal = []
  if(index === 0){
  data.forEach((element, index, arr) => {
      labes.push(element.eqpId)
      _terget[element.eqpId] = []
      element.oeeBMachineStatusList.forEach((item) => {
        const time1 = JSON.parse(JSON.stringify(item.data[1]))
        const time2 = JSON.parse(JSON.stringify(item.data[2]))
        item.data[0] = arr.length - index - 1
        item.data[1] = moment(time1).unix() - moment(dataTime).unix()
        item.data[2] = moment(time2).unix() - moment(dataTime).unix()
        _terget[element.eqpId].push({
          itemStyle: { color: item.color },
          name: item.status,
          value: item.data
        })
      })
    })
  }

  Object.values(JSON.parse(JSON.stringify(_terget))).map((item) => {
    finaVal.push(...item)
  })

  return {
    tooltip: {
      position: function (point, qwe) {
        var pointX = point[0]
        var pointY = point[1]
        if(window.innerWidth - pointX < 500 ){
          return [pointX - 250, pointY + 30]
        } else {
          return [pointX, pointY + 30]
        }
      },
    formatter: function (params) {
      if(params.value){
        return `
        设备ID: ${params.value[3]}<br/>
        设备状态: ${params.name}<br/>
        R Code描述: ${params.value[13]}(${params.value[4]})<br/>
        开始时间: ${moment((moment(dataTime).unix() + params.value[1])  * 1000).format('YYYY-MM-DD HH:mm:ss')}<br/>
        结束时间: ${moment((moment(dataTime).unix() + params.value[2])  * 1000).format('YYYY-MM-DD HH:mm:ss')}<br/>
        持续时长: ${params.value[6]}分(${(Number(params.value[6]) * 60).toFixed(2)}秒)<br/>
        读报警时间: ${params.value[5] ? params.value[5] : '--'}<br/>
        报警文本: ${params.value[8] ? params.value[8] : '--'}<br/>
        报警ID: ${params.value[9]? params.value[9] : '--'}<br/>
        源报警ID: ${params.value[10] ? params.value[10] : '--'}<br/>
        源报警设备类型: ${params.value[12] ? params.value[12] : '--'}<br/>
        `
      }
    }
    },
    grid: {
      left: '0%',
      right: '45px',
      top: '2%',
      bottom: '2%',
      containLabel: true
    },
    xAxis: {
      min: 0,
      max: 'dataMax',
      position: 'top',
      axisPointer: {
        show: true,
        label: {
          formatter: ({ value }) => {
            return moment((moment(dataTime).unix() + value) * 1000).format("MM-DD HH:mm:ss")
          }
        }
      },
        type: 'value',
        axisTick: {
          alignWithLabel: false
        },
        boundaryGap: false, // 设置x轴的边界间隔为false
        // min: echartsDataTimeMin, //最小时间（秒）!!!!!!!!!!
        // max: echartsDataTimeMax, //最大时间（秒）!!!!!!!!
        axisLabel: {
          formatter: function (value, index) {
            return moment((moment(dataTime).unix() + value) * 1000).format("MM-DD HH:mm:ss")
          }
        }
    },
    yAxis: {
      // data: ["H05-PHLX-01\nMBB区片花蓝机01", "H05-MBB-01\nMBB单线01", "aef", "sdfdsfdssd"]
      data: labes.reverse()
      // show: false, // 不显示坐标轴线、坐标轴刻度线和坐标轴上的文字
      // axisTick: {
      //   show: false // 不显示坐标轴刻度线
      // },
      // axisLine: {
      //   show: false // 不显示坐标轴线
      // },
      // axisLabel: {
      //   show: false // 不显示坐标轴上的文字
      // },
      // splitLine: {
      //   show: false // 不显示网格线
      // }
    },
    series: [
      // 用空bar来显示四个图例
      // { name: state[0], type: 'bar', data: [] },
      // { name: state[1], type: 'bar', data: [] },
      // { name: state[2], type: 'bar', data: [] },
      // { name: state[3], type: 'bar', data: [] },
      {
        type: 'custom',
        renderItem: function (params, api) {
          var categoryIndex = api.value(0)
          var start = api.coord([api.value(1), categoryIndex])
          var end = api.coord([api.value(2), categoryIndex])
          var height = 30

          return {
            type: 'rect',
            shape: echarts.graphic.clipRectByRect({
              x: start[0],
              y: start[1] - height / 2,
              width: end[0] - start[0],
              height: height
            }, {
              x: params.coordSys.x,
              y: params.coordSys.y,
              width: params.coordSys.width,
              height: params.coordSys.height
            }),
            style: api.style()
          }
        },
        encode: {
          x: [1, 2],
          y: 0
        },
        data: finaVal
      }
    ]
  }
}

const cellRenderer = (params) => {
  if(params.value){
    return `<div style="background: ${params.data.color}; width: 80%; height: 70%; line-height: 20px; margin: 3px 6px;">${params.value}</div>`
  } else {
    return `<div style="background: #00ff00; width: 80%; height: 70%; line-height: 20px; margin: 4px 6px;">RUN</div>`
  }
}

const cellRendererPre = (params) => {
  return `<div style="background: ${params.data.preColor}; width: 80%; height: 70%; line-height: 20px; margin: 3px 6px;">${params.value}</div>`
}
const commonColumn = [
  { headerName: "父设备", field: "topId", width: 100, pinned: 'left' },
  { headerName: "设备ID", field: "machineId", width: 100, pinned: 'left' },
  { headerName: "开始时间", field: "createTime", minWidth: 160, flex: 1 },
  { headerName: "结束时间", field: "endTime", minWidth: 160, flex: 1 },
  { headerName: "持续时长/分", field: "keepTime", minWidth: 100, flex: 1 },
  { headerName: "反应时长/分", field: "reactTime", minWidth: 100, flex: 1 },
  { headerName: "前状态", field: "status", minWidth: 70, flex: 1, cellRenderer: cellRendererPre },
  { headerName: "现状态", field: "lastStatus", minWidth: 70, flex: 1, cellRenderer },
  { headerName: "RCode", field: "rcode", minWidth: 100, flex: 1 },
  { headerName: "Code描述", field: "codeDescription", minWidth: 100, flex: 1 },
  { headerName: "制造类型", field: "productType", minWidth: 100, flex: 1 },
  { headerName: "源设备ID", field: "sourceMachineId", minWidth: 100, flex: 1 },
  { headerName: "源设备类型", field: "sourceMachineType", minWidth: 100, flex: 1 },
  { headerName: "停机区分", field: "shutdownType", minWidth: 100, flex: 1 }

]

export const allColumn = [
  ...commonColumn,
  { headerName: "损失计件", field: "lossCount", minWidth: 100, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "累计持续时长/分", field: "totalTime", minWidth: 120, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "累计反映时长/分", field: "totalReactTime", minWidth: 120, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "备注", field: "remark", minWidth: 400, flex: 1, tooltipField:'remark' }
]

export const downColumn = [
  ...commonColumn,
  { headerName: "报警ID", field: "alarmId", minWidth: 70, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "发报警时间", field: "alarmSendTime", minWidth: 150, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "读报警时间", field: "alarmReadTime", minWidth: 150, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "消报警时间", field: "alarmEndTime", minWidth: 150, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "报警文本", field: "alarmTxt", minWidth: 200, flex: 1, filter: 'agMultiColumnFilter', tooltipField:'alarmTxt' },
  { headerName: "读报警损失/分", field: "alarmReadDateTime", minWidth: 120, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "消报警损失/分", field: "alarmLossDateTime", minWidth: 120, flex: 1, filter: 'agMultiColumnFilter' },

  { headerName: "报警等级", field: "alarmLevel", minWidth: 100, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "报警部位", field: "alarmLocate", minWidth: 150, flex: 1, filter: 'agMultiColumnFilter', tooltipField:'alarmLocate' },
  { headerName: "损失计件", field: "lossCount", minWidth: 100, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "累计持续时长/分", field: "totalTime", minWidth: 120, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "累计反映时长/分", field: "totalReactTime", minWidth: 120, flex: 1, filter: 'agMultiColumnFilter' },
  { headerName: "备注", field: "remark", minWidth: 400, flex: 1, tooltipField:'remark' }
]

commonColumn.forEach((item) => {
  item.filter = 'agMultiColumnFilter'
})

const summary = [
  { headerName: "设备ID", field: "machineId", width: 120 },
  { headerName: "生产", field: "t1000", minWidth: 60, flex: 1 },
  { headerName: "待料", field: "t1100", minWidth: 60, flex: 1, headerClass: 'custom-orange' },
  { headerName: "堵料", field: "t1200", minWidth: 60, flex: 1, headerClass: 'custom-orange' },
  { headerName: "无计划", field: "t1300", minWidth: 60, flex: 1, headerClass: 'custom-orange' },
  { headerName: "设备故障", field: "t2000", minWidth: 60, flex: 1 },
  { headerName: "Interlock", field: "t3000", minWidth: 70, flex: 1 },
  { headerName: "原材料故障", field: "t4100", minWidth: 70, flex: 1 },
  { headerName: "辅材料故障", field: "t4200", minWidth: 70, flex: 1 },
  { headerName: "应急报警", field: "t6112", minWidth: 70, flex: 1, headerClass: 'custom-blue' },
  { headerName: "生产5S", field: "t6111", minWidth: 60, flex: 1, headerClass: 'custom-blue' },
  { headerName: "一级保养", field: "t5100", minWidth: 60, flex: 1, headerClass: 'custom-blue' },
  { headerName: "定期PM", field: "t5200", minWidth: 60, flex: 1, headerClass: 'custom-blue' },
  { headerName: "设备非定期", field: "t6100", minWidth: 70, flex: 1, headerClass: 'custom-blue' },
  { headerName: "品质非定期", field: "t6200", minWidth: 70, flex: 1, headerClass: 'custom-blue' },
  { headerName: "改造改善", field: "t8000", minWidth: 60, flex: 1, headerClass: 'custom-blue' },
  { headerName: "实验借机", field: "t7000", minWidth: 60, flex: 1, headerClass: 'custom-blue' },
  { headerName: "材料更换", field: "t9100", minWidth: 60, flex: 1, headerClass: 'custom-blue' },
  { headerName: "版型变更", field: "t9200", minWidth: 60, flex: 1, headerClass: 'custom-blue' },
  { headerName: "异常PM", field: "t10000", minWidth: 60, flex: 1 },
  { headerName: "设备OFF", field: "off", minWidth: 60, flex: 1 }
]

const cellRendererSummary = (params) => {
  let _target = null
  Object.values(params.data).forEach((item) => {
    if(Number(item)){
      _target = _target + Number(item)
    }
  })
  return _target.toFixed(0)+'.00'
}

const cellRendererSummaryPercent = (params) => {
  let _target = null
  Object.values(params.data).forEach((item) => {
    if(Number(item.replace(/%/g, ""))){
      _target = _target + Number(item.replace(/%/g, ""))
    }
  })
  return _target.toFixed(0)+'.00%'
}

export const columnSummary = [
  ...summary,
  { headerName: "合计", field: "startStopStatus", minWidth: 60, flex: 1, cellRenderer: cellRendererSummary }
]

export const columnSummaryPercent = [
  ...summary,
  { headerName: "合计", field: "startStopStatus", minWidth: 60, flex: 1, cellRenderer: cellRendererSummaryPercent }
]